function applyTemplate (t, r){
	var tmpStr = t.join('');
	for(var i in r){
		while (tmpStr.indexOf('{'+i+'}')>-1) {
			tmpStr = tmpStr.replace('{'+i+'}', r[i])
		}
	}
	return tmpStr;
}

function getUniqueIdentifier() {
	return new String(Math.round(Math.random()*100000000));
}

var answerIdentifiers = new Array();

function add_survey_answer(data) {
	var r = data ? data : {
		answer_id : '',
		answer_text : '',
		answer_weight : ''
	};
	
	r['answer_unique'] = getUniqueIdentifier();
	r['answer_number'] = answerIdentifiers.length + 1;
	
	answerIdentifiers.push(r['answer_unique']);
	
	jQuery('#question_answer_empty_row').before(applyTemplate(answerItemTemplate, r));
	jQuery('#question_answer_answer_'+r.answer_unique+' textarea').wysiwyg();
}

function remove_survey_answer(answer_unique){
	jQuery('#question_answer_'+answer_unique).remove();
	for (var i=0; i< answerIdentifiers.length; i++) {
		if (answerIdentifiers[i] == answer_unique) {
			answerIdentifiers.splice(i, 1);
			break;
		}
	}
	for (var i=0; i< answerIdentifiers.length; i++) {
		jQuery('#question_answer_number_'+answerIdentifiers[i]).html(i+1);
	}
}

function submit_survey_answers() {
	jQuery('#question_answer_identifiers').val(answerIdentifiers.join(','));
}

function toggle_code(button, id, view_text, hide_text) {
	if (button.value == view_text) {
		jQuery('#code_view_'+id).html('&lt;!-- wp_surveys id="'+id+'" --&gt;');
		jQuery('#code_view_'+id).css('display', 'block');
		button.value = hide_text; 
	} else {
		jQuery('#code_view_'+id).css('display', 'none');
		button.value = view_text; 
	}
}
